package com.jctrip.hotel.route.service;

import com.jctrip.hotel.domain.dao.HtOrderRouteRecordDao;
import com.jctrip.hotel.domain.entity.HtOrderRouteRecord;
import com.jctrip.hotel.domain.entity.HtOrderSourceRecord;
import com.jctrip.hotel.domain.entity.HtRouteInfo;
import com.jctrip.hotel.route.common.ThreadLocalSession;
import com.jctrip.hotel.route.model.param.UpdateOrderParam;
import com.jctrip.hotel.route.model.result.UpdateOrderResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 更新订单接口-服务
 */
@Service
public class UpdateOrderService extends RouteService {

    @Autowired
    private HtOrderRouteRecordDao htOrderRouteRecordDao;

    public UpdateOrderResult execute(UpdateOrderParam param) {
        HtRouteInfo htRouteInfo = ThreadLocalSession.get().getRouteInfo();
        String routeId = htRouteInfo.getRouteId();
        HtOrderRouteRecord htOrderRouteRecord = param.getRouteOrderId() == null
                ? getOrderRouteRecord(param.getOrderId())
                : getOrderRouteRecord(routeId, param.getRouteOrderId());
        if (htOrderRouteRecord == null) {
            throw new RuntimeException("orderId或者routeOrderId无效");
        }
        if (!htOrderRouteRecord.getRouteId().equals(routeId)) {
            throw new RuntimeException("没有权限的订单");
        }
        HtOrderSourceRecord htOrderSourceRecord = getOrderSourceRecord(htOrderRouteRecord.getOrderId());
        if (htOrderSourceRecord == null) {
            throw new RuntimeException("没有供应下单记录");
        }
        // 更新渠道订单
        updateOrderRouteRecord(htOrderRouteRecord, param);
        return UpdateOrderResult.builder().build();
    }

    private void updateOrderRouteRecord(
            HtOrderRouteRecord htOrderRouteRecord,
            UpdateOrderParam param) {
        if (param.getRouteOrderStatus() != null) {
            htOrderRouteRecord.setRouteOrderStatus(param.getRouteOrderStatus());
        }
        if (param.getOrderPaymentTime() != null) {
            htOrderRouteRecord.setOrderPaymentTime(param.getOrderPaymentTime());
        }
        htOrderRouteRecordDao.updateById(htOrderRouteRecord);
    }
}
